package com.losl.framework.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.losl.common.core.domain.Result;
import com.losl.common.core.domain.BaseController;
import com.losl.common.core.domain.entity.SysUser;
import com.losl.common.core.domain.model.LoginUser;
import com.losl.common.exception.CustomException;
import com.losl.common.util.ServletUtils;
import com.losl.common.util.StringUtils;
import com.losl.framework.web.service.TokenService;
import com.losl.system.pojo.Posts;
import com.losl.system.service.PostsService;
import com.losl.system.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@RestController("/user")
@Api(value = "用户-API", tags = "用户相关接口")
public class UserDataCcontroller extends BaseController{
    @Autowired
    private SysUserService userService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private AuthenticationManager manager;
    @Autowired
    private PostsService postsService;

    @PreAuthorize("@ps.hasPermission('sys:user:detail')")
    @ApiOperation("获取用户详细信息")
    @GetMapping("/detail")
    public Result detail(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNull(loginUser)) {
            throw new CustomException("用户异常");
        }
        SysUser user = loginUser.getUser();
        return Result.success().put("data",user);
    }

    @PreAuthorize("@ps.hasPermission('sys:user:update')")
    @ApiOperation("修改用户信息")
    @ApiImplicitParam(name = "user", value = "用户表实体", paramType = "query", dataType = "SysUser")
    @PutMapping("/update")
    public Result update(@RequestBody @Valid SysUser user) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user1 = loginUser.getUser();
        user.setUserId(user1.getUserId());
        boolean flag = userService.updateById(user);
        loginUser.setUser(userService.getById(user1.getUserId()));
        tokenService.refreshToken(loginUser);
        return Result.success().put("flag", flag);
    }

    @PreAuthorize("@ps.hasPermission('sys:user:password')")
    @ApiOperation("修改密码")
    @ApiImplicitParam(name = "user", value = "用户表实体", paramType = "query", dataType = "SysUser")
    @PostMapping("/update/password")
    public Result updatePassword(@RequestBody @Valid SysUser user) {
        System.out.println(user);

        if (StringUtils.isEmpty(user.getPassword()))
        {
            throw new CustomException("密码错误");
        }
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        try {
            manager.authenticate(new UsernamePasswordAuthenticationToken(loginUser.getUsername(),user.getPassword(),loginUser.getAuthorities()));
        }catch (Exception e){
            throw new CustomException("密码错误");
        }

        String password = passwordEncoder.encode(user.getPassword());
        SysUser userDB = userService.getById(loginUser.getUser().getUserId());
        userDB.setPassword(passwordEncoder.encode(user.getUsername()));
        System.out.println(userDB);
        return Result.success().put("key", userService.updateById(userDB));
    }



    @PreAuthorize("@ps.hasPermission('sys:user:password')")
    @GetMapping("/post")
    public Result myPost() {
        Page<Posts> page = getPage();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Integer userId = loginUser.getUser().getUserId();
        QueryWrapper<Posts> wrapper = new QueryWrapper<>();
        wrapper.eq("author_id",userId);
        Page<Posts> page1 = postsService.page(page, wrapper);
        return Result.success().put("data",page1);
    }
}
